// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';
// const isProduction = true;
/**
 * localStorage 的基础操作封装
 */
import {decrypt, encrypt} from '@/utils/jsencrypt';

const setStorageL = (key: string, value: any) => {
  if (isProduction) {
    localStorage.setItem(key, encrypt(JSON.stringify(value)));
  } else {
    localStorage.setItem(key, JSON.stringify(value));
  }
}

const getStorageL = (key: string) => {
  const item = localStorage.getItem(key);
  if (item != null) {
    if (isProduction) {
      try {
        return JSON.parse(decrypt(item));
      } catch (e) {
        removeStorageL(key);
        return null;
      }
    } else {
      try {
        return JSON.parse(item);
      } catch (e) {
        removeStorageL(key);
        return null;
      }
    }
  }
  return null;
}

const removeStorageL = (key: string) => {
  localStorage.removeItem(key);
}

/**
 * localStorage 的基础操作封装
 */
const setStorageS = (key: string, value: any) => {
  if (isProduction) {
    sessionStorage.setItem(key, encrypt(JSON.stringify(value)));
  } else {
    sessionStorage.setItem(key, JSON.stringify(value));
  }
}

const getStorageS = (key: string) => {
  const item = sessionStorage.getItem(key);
  if (item != null) {
    if (isProduction) {
      try {
        return JSON.parse(decrypt(item));
      } catch (e) {
        removeStorageL(key);
        return null;
      }
    } else {
      try {
        return JSON.parse(item);
      } catch (e) {
        removeStorageL(key);
        return null;
      }
    }
  }
  return null;
}

const removeStorageS = (key: string) => {
  sessionStorage.removeItem(key);
}

/**
 * 清空所有
 */
const clearStore = () => {
  sessionStorage.clear();
  // localStorage.clear();
  removeStorageL(CONST.token);
}

const CONST = !isProduction ? {
  // token key
  token: 'token',
  router: 'router',
  avatar: 'avatar',
  collapse: 'collapse',
  projectInfo: 'projectInfo',
  addRoutes: 'addRoutes',
  userInfo: 'userInfo',
  name: 'name',
  logoSrc: 'logoSrc',
  permission: 'permission',
  rememberMe: 'rememberMe',
} : {
  token: 'a',
  router: 'b',
  avatar: 'c',
  collapse: 'd',
  projectInfo: 'e',
  addRoutes: 'f',
  userInfo: 'g',
  name: 'h',
  logoSrc: 'i',
  permission: 'j',
  rememberMe: 'k',
};

export default {
  setStorageL,
  getStorageL,
  removeStorageL,
  setStorageS,
  getStorageS,
  removeStorageS,
  clearStore,
  CONST,
};
